<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>新建单据</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="../css/base.css">
    <link rel="stylesheet" href="../../css/element-ui.css" />
    <link rel="stylesheet" href="../css/index.css">
    <script src="../../js/common/jquery.min.js"></script>
    <script src="../../js/common/browser.min.js"></script>
    <script src="../../js/common/vue.js"></script>
    <script src="../../js/common/element-ui.js"></script>
    <script src="../js/common/common.js"></script>
</head>

<body>
    <div id="wtNewly">
        <div class="container">
            <div class="rj-header">
                <p class="nav">
                    <span class="default">您现在所在的位置:</span>
                    <span class="direction">{{prams.breadcrumb}}</span>
                </p>
                <div class="search-container">
                    <div class="item">
                        <label>单据流水号</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.BillSN" />
                    </div>
                    <div class="item">
                        <label>录入人</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.InputUserName" />
                    </div>
                    <div class="item">
                        <label>审核人</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.AuditUserName" />
                    </div>
                    <div class="item">
                        <label>登账人</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.AcceptUserName" />
                    </div>
                    <div class="item">
                        <label>结账人</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.CloseUserName" />
                    </div>
                    <div class="item">
                        <label>入库科室</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.InDeptName" />
                    </div>
                    <div class="item">
                        <label>录入时间</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.InputTime" />
                    </div>
                    <div class="item">
                        <label>审核时间</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.AuditTime" />
                    </div>
                    <div class="item">
                        <label>登账时间</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.AcceptTime" />
                    </div>
                    <div class="item">
                        <label>结账时间</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.CloseTime" />
                    </div>
                    <div class="item">
                        <label>出库科室</label>
                        <input type="text" class="forbid" disabled="disabled" :value="Head.OutDeptName" />
                    </div>
                    <div class="item">
                        <label>备注</label>
                        <textarea type="text" rows="1" v-model="Head.Comment" :disabled="isSaved" /></textarea>
                    </div>
                    <div class="item">
                        <label>单据状态</label>
                        <input type="text" class="forbid" disabled="disabled" :value="StatusName" />
                    </div>
                </div>
            </div>
            <div class="btn-group">

                <el-button type="success" v-if="!isSaved" @click="handle">保存</el-button>
                <el-button type="success" v-else @click="editor" :disabled="!operations.isEditor">修改</el-button>
                <el-button type="info" :disabled="!operations.isSend" @click="send">提交申请</el-button>
               
                <el-button type="info" @click="back">返回</el-button>
            </div>
            <div class="table-wrapper">

                <table class="bill-table">
                    <tr style="background-color: #ddd;">
                        <th v-for="(data,index) in tableData">
                            <p>{{data}}</p>
                        </th>
                        <th>
                            <p>操作</p>
                        </th>
                    </tr>
                    <tr :class="{active:active==index}" v-if="BillData.length" v-for="(v,index) in BillData">
                        <!-- @click="check(index,v.BillSN)"  @dblclick="href(v.BillSN)" -->
                        <td>
                            <p>{{v.GoodsCode}}</p>
                        </td>
                        <td>
                            <p>{{v.GoodsName}}</p>
                        </td>
                        <td>
                            <p>{{v.GoodsSpec}}</p>
                        </td>
                        <td>
                            <p>{{v.BoxUnit}}</p>
                        </td>
                        <td>
                            <p><input type="number" class="setInput" v-model="v.ApplyNum" :disabled="isSaved" /></p>
                        </td>
                        <!-- <td>
                            <p>{{v.GoodsCount}}</p>
                        </td> -->
                        <td>
                            <p>{{v.RefPrice}}</p>
                        </td>
                        <td>
                            <p>{{v.consultMoney}}</p>
                        </td>
                        <td>
                            <p><input class="setInput" v-model="v.Comment" :disabled="isSaved" /></p>
                        </td>
                        <td>
                            <p>{{v.CardNumberList}}</p>
                        </td>
                        <td>
                            <p>{{v.ChargeCode}}</p>
                        </td>
                        <td>
                            <p><input type="number" class="setInput" v-model="v.ActualSendNum" disabled="disabled" /></p>
                        </td>
                        <td>
                            <p>
                                <el-button type="primary" size="mini" @click="del(v,index)" :disabled="isSaved">删除</el-button>
                            </p>
                        </td>
                    </tr>
                    <tr v-show="!isSaved">
                        <td v-for="(data,index) in tableHeard">
                            <p><input type="text" autofocus @keyup.enter="popup" style="height: 26px;width: 90%;text-indent: 1em;border: none;" v-if="index == 0" /></p>
                            </th>
                    </tr>
                </table>
            </div>

        </div>
    </div>
    <script>
        var app = new Vue({
            el: '#wtNewly',
            data: {
                prams: JSON.parse(GetRequest().param),
                userJS: JSON.parse(localStorage.getItem("userJS")),
                isUserJS: localStorage.getItem("userJS") && JSON.parse(localStorage.getItem("userJS")).length > 0 ? true : false,
                BillSN: GetRequest().BillSN ? JSON.parse(GetRequest().BillSN) : null,
                forbid: true,
                userID: JSON.parse(localStorage.getItem('currentUser')).Ygid,
                inputTimeStart: '',
                inputTimeEnd: '',
                saveOrUpdate: "save",
                isSaved: false,
                isDisabled: true,
                tableData: ['物品代码', '物品名称', '规格型号', '计量单位', '申请数', '参考单价', '参考金额', '备注', '卡片号列表', '收费代码', '实发数'],
                tableHeard: new Array(13),
                BillData: [],
                active: 0,
                inRooms: [],
                selectedRoom: "all",
                Head: {
                    "BillSN": "",
                    "BillType": null,
                    "BillTypeStr": "ly",
                    "AdditionalReason": null,
                    "AdditionalReasonTypeStr": "",
                    "OutDeptAccountID": JSON.parse(GetRequest().OutDept).DeptAccountID,
                    "InDeptAccountID": JSON.parse(localStorage.getItem('deptInfo')).DeptAccountID,
                    "OutDeptCode": JSON.parse(GetRequest().OutDept).Ksdm,
                    "OutDeptName": JSON.parse(GetRequest().OutDept).Ksmc,
                    "InDeptCode": JSON.parse(localStorage.getItem('deptInfo')).Ksdm,
                    "InDeptName": JSON.parse(localStorage.getItem('deptInfo')).Ksmc,
                    "InputUserID": JSON.parse(localStorage.getItem('currentUser')).Ygid,
                    "InputUserName": JSON.parse(localStorage.getItem('currentUser')).Xm,
                    "SendUserID": null,
                    "SendUserName": null,
                    "AduitUserID": null,
                    "AuditUserName": null,
                    "DeliverUserID": null,
                    "DeliverUserName": null,
                    "AcceptUserID": null,
                    "AcceptUserName": null,
                    "CloseUserID": null,
                    "CloseUserName": null,
                    "InputTime": "",
                    "SendTime": null,
                    "AuditTime": null,
                    "DeliverTime": null,
                    "AcceptTime": null,
                    "CloseTime": null,
                    "Comment": "",
                    "Status": null,
                    "StatusStr": "",
                    "PrintTimes": 0,
                    "GoodsBookID": JSON.parse(GetRequest().param).Openparm.GoodsBook,
                    "InDeptAccountName": JSON.parse(localStorage.getItem('deptAccount')).DeptAccountName,
                    "OutDeptAccountName": JSON.parse(GetRequest().OutDept).Ksmc,
                    "HelpNumber": null,
                    "kc_fs": "",
                    "BillSource": null

                },
                Detail: {
                    "ChargeCode": "",
                    "BillDetailSN": "",
                    "BillSN": "",
                    "GoodsID": "",
                    "GoodsName": "",
                    "ApplyNum": 0,
                    "ActualSendNum": 0,
                    "RefPrice": 0,
                    "Index": 0,
                    "HasCard": false,
                    "CardNumberList": " ",
                    "GoodsCode": "",
                    "DetailBatches": [],
                    "PyCode": "",
                    "BoxUnit": "",
                    "GoodsSpec": "",
                    "Comment": "",
                    "AfterTaxPrice": 0.0
                },
                newBillData: [],
            },
            created: function() {
                console.log(this.prams)
                if (this.BillSN) {
                    this.isSaved = !this.isSaved
                    this.getBills(this.BillSN)
                }
                // var that = this;
                // this.getInRoom().then(function() {
                //     if (that.BillSN) {
                //         that.isSaved = !that.isSaved
                //         that.getBills(that.BillSN)
                //     }
                // })
            },
            computed: {
                StatusName: function() {
                    return this.toName(this.Head.StatusStr)
                },
                operations: function() {
                    return this.operationRights(this.Head.StatusStr)
                },
                isAudit: function() {
                    return this.Head.StatusStr && this.Head.StatusStr == "lr"
                },
                isChecked: function() {
                    return this.Head.StatusStr && this.Head.StatusStr == "fs"
                }
            },
            watch: {
                selectRoomName: function(curVal, oldVal) {
                    this.$set(this.Head, "RoomInfo", curVal)　　　　　　　　
                },
                selectedRoom: function(curVal, oldVal) {
                    var that = this
                    for (var i = 0; i < this.inRooms.length; i++) {
                        if (curVal == that.inRooms[i].RoomID) {
                            that.Head.InRoomID = that.inRooms[i].RoomID;
                            that.Head.InRoomCode = that.inRooms[i].RoomCode;
                            that.Head.InRoomName = that.inRooms[i].RoomName
                        }
                    }
                    console.log(that.Head)　　　　　　　　
                },
                BillData: {　　　　
                    handler(newValue, oldValue) {
                        newValue.forEach(function(item) {
                            item.consultMoney = Number(item.ApplyNum * item.RefPrice).toFixed(2)
                        })　　　　
                    },
                    　　　　deep: true　　
                },
                　　　　　　　

                　　　　　　
            },
            methods: {
                operationRights: function(value) {
                    if (!value) return ''
                    value = value.toString()
                    var operations = {}
                    switch (value) {
                        case "lr":
                            operations = {
                                isEditor: true,
                                isSend: true,
                                isSh: false,
                                isLy: false,
                                isZf: true
                            }
                            break;

                        case "fs":
                            operations = {
                                isEditor: true,
                                isSend: false,
                                isSh: true,
                                isLy: false,
                                isZf: true
                            }
                            break;
                        case "sh":
                            operations = {
                                isEditor: false,
                                isSend: false,
                                isSh: false,
                                isLy: true,
                                isZf: false
                            }
                        case "ly":
                            operations = {
                                isEditor: false,
                                isSend: false,
                                isSh: false,
                                isLy: false,
                                isZf: false
                            }
                        case "zf":
                            operations = {
                                isEditor: false,
                                isSend: false,
                                isSh: false,
                                isLy: false,
                                isZf: false
                            }
                            break;
                        default:
                            operations = {
                                isEditor: true,
                                isSend: false,
                                isSh: false,
                                isLy: false,
                                isZf: false
                            }
                    }
                    return operations
                },
                toName: function(value) {
                    if (!value) return ''
                    value = value.toString()
                    var StatusName = null;
                    switch (value) {
                        case "lr":
                            StatusName = "录入"
                            break;
                        case "fs":
                            StatusName = "发送"
                            break;
                        case "sh":
                            StatusName = "审核"
                            break;
                        case "ly":
                            StatusName = "完成"
                            break;
                        case "dz":
                            StatusName = "登账"
                            break;
                        case "jz":
                            StatusName = "结账"
                            break;
                        case "zf":
                            StatusName = "作废"
                            break;
                    }
                    return StatusName
                },
                setToEqual: function(obj1, obj2) {
                    if (!obj1 || !obj2) return;
                    var keys1 = Object.keys(obj1);
                    var keys2 = Object.keys(obj2);
                    for (var i = 0; i < keys1.length; i++) {
                        for (var j = 0; j < keys2.length; j++) {
                            if (keys1[i] == keys2[j]) {
                                obj1[keys1[i]] = obj2[keys2[j]];
                                break;
                            }
                        }
                    }
                },
                update: function() {
                    var that = this
                    for (var i = 0, len = this.BillData.length; i < len; i++) {
                        if (!/^[0-9]+$/.test(this.BillData[i].ApplyNum || this.BillData[i].ApplyNum <= 0)) {
                            that.$message.error('申请数应为大于0的整数！');
                            return false
                        }

                    }
                    var obj = {};
                    obj.Head = {
                        "InDeptAccountID": this.Head.InDeptAccountID,
                        "InDeptCode": this.Head.InDeptCode,
                        "OutDeptAccountID": this.Head.OutDeptAccountID,
                        "OutDeptCode": this.Head.OutDeptCode,
                        "PrintTimes": this.Head.PrintTimes,
                        "Comment": this.Head.Comment,
                        "GoodsBookID": this.Head.GoodsBookID,
                        "MoveBillReasonType": this.Head.MoveBillReasonType,
                        "MoveBillReasonTypeStr": this.Head.MoveBillReasonTypeStr,
                        "BillSN": this.Head.BillSN,
                        "InputTime": this.Head.InputTime,
                        "InputUserID": this.Head.InputUserID,
                        "Status": this.Head.Status,
                        "StatusStr": this.Head.StatusStr,
                        "BillSource": 1
                    }
                    obj.Details = this.BillData
                    var parms = {
                        batchSelections: '[]',
                        className: 'DrawBillManager',
                        method: 'ModifyDrawBill',
                        drawBill: JSON.stringify(obj),
                        userID: this.userID
                    }
                    this._fetch(parms).then(function() {
                        that.getBills(that.Head.BillSN).then(function() {
                            that.isSaved = !that.isSaved
                            that.isDisabled = !that.isDisabled
                            that.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                        })


                    })

                },
                editor: function() {
                    var that = this
                    that.isSaved = !that.isSaved
                    this.saveOrUpdate = "update"

                },
                handle: function() {
                    switch (this.saveOrUpdate) {
                        case "save":
                            this.save();
                            break;
                        case "update":
                            this.update();
                            break;
                    }
                },
                getBills: function(billSN) {
                    var that = this
                    var condition = this.conditionModel("a.lsh", null, "Equal", billSN, "String")
                    var parms = {
                        className: 'MoveBillQueryManager',
                        method: 'GetBill',
                        condition: JSON.stringify(condition),
                        billSN: billSN
                    }
                    return this._fetch(parms).then(function(data) {
                        that.setToEqual(that.Head, data.Head)
                        that.BillData = data.Details
                    });
                },
                save: function() {
                    var that = this
                    if (this.BillData.length == 0) {
                        that.$message.error('请新建领用单');
                        return false
                    }

                    for (var i = 0, len = this.BillData.length; i < len; i++) {
                        if (!/^[0-9]+$/.test(this.BillData[i].ApplyNum || this.BillData[i].ApplyNum <= 0)) {
                            that.$message.error('申请数应为大于0的整数！');
                            return false
                        }

                    }
                    var obj = {}
                    var Head = {

                        "OutDeptAccountID": JSON.parse(GetRequest().OutDept).DeptAccountID,
                        "InDeptAccountID": JSON.parse(localStorage.getItem('deptInfo')).DeptAccountID,
                        "OutDeptCode": JSON.parse(GetRequest().OutDept).Ksdm,
                        "InDeptCode": JSON.parse(localStorage.getItem('deptInfo')).Ksdm,
                        "Comment": "",
                        "PrintTimes": 0,
                        "GoodsBookID": JSON.parse(GetRequest().param).Openparm.GoodsBook,
                        "MoveBillReasonType": "zc",
                        "MoveBillReasonTypeStr": "zc",
                        "BillSource": 1
                    }
                    var Details = [];
                    this.BillData.forEach(function(item, index) {
                        var Detail = {
                            "BillDetailSN": "",
                            "BillSN": "",
                            "GoodsID": item.GoodsID,
                            "ApplyNum": item.ApplyNum,
                            "ActualSendNum": item.ActualSendNum,
                            "RefPrice": item.RefPrice,
                            "CardNumberList": "",
                            "HasCard": false,
                            "Sort": index+1,
                            "Comment": item.Comment
                        }
                        Details.push(Detail)
                    })
                    obj.Head = Head
                    obj.Details = Details
                    var parms = {
                        className: 'DrawBillManager',
                        method: 'InputDrawBill',
                        drawBill: JSON.stringify(obj),
                        userID: this.userID,
                        batchSelections: '[]'
                    }
                    this._fetch(parms).then(function(data) {
                        that.getBills(data).then(function() {
                            that.isSaved = !that.isSaved
                            that.isDisabled = !that.isDisabled
                            that.$message({
                                message: '保存成功',
                                type: 'success'
                            });
                        })


                    })

                },
                send: function() {
                    var that = this;
                    if (this.saveOrUpdate !== "save") {
                        that.$message.error('请先保存');
                        return false;
                    }
                    var parms = {
                        className: 'DrawBillManager',
                        method: 'SendDrawBill',
                        billSN: this.Head.BillSN,
                        userID: this.userID
                    }
                    this._fetch(parms).then(function(data) {
                        that.getBills(that.Head.BillSN).then(function() {
                            // that.isSaved = !that.isSaved
                            //that.isDisabled = !that.isDisabled
                            that.$message({
                                message: '发送成功',
                                type: 'success'
                            });
                        })
                    })
                },
                commit: function() {
                    var that = this;
                    if (!this.isUserJS) {
                        this.$message.error('很抱歉你没有权限审核！');
                        return false
                    }
                    var parms = {
                        className: 'TwoLevelStockManager',
                        method: 'AuditDrawBill',
                        billSN: this.Head.BillSN,
                        details: JSON.stringify(this.BillData),
                        userID: this.userID,
                    }
                    this._fetch(parms).then(function(data) {
                        that.getBills(that.Head.BillSN).then(function() {
                            // that.isSaved = !that.isSaved
                            //that.isDisabled = !that.isDisabled
                            that.$message({
                                message: '审核成功',
                                type: 'success'
                            });
                        })
                    })

                },
                revoke: function() {
                    var that = this;
                    if (!this.isUserJS && !this.Head.StatusStr !== 'sh') {
                        this.$message.error('很抱歉你没有权限！');
                        return false
                    }
                    var parms = {
                        className: 'TwoLevelStockManager',
                        method: 'UndoAuditDrawBill',
                        billSN: this.Head.BillSN,
                        userID: this.userID
                    }
                    this._fetch(parms).then(function(data) {
                        that.getBills(that.Head.BillSN).then(function() {
                            that.$message({
                                message: '撤销成功',
                                type: 'success'
                            });
                        })
                    })


                },
                receive: function() {
                    var that = this;
                    if (!this.isUserJS) {
                        this.$message.error('很抱歉你没有权限！');
                        return false
                    }
                    if (!this.Head.DrawUserName || this.Head.DrawUserName == "") {
                        this.$message.error('请输入领用人工号！');
                        return false
                    }
                    var parms = {
                        className: 'TwoLevelStockManager',
                        method: 'DrawDrawBill',
                        billSN: this.Head.BillSN,
                        userID: this.Head.DrawUserName,
                    }
                    this._fetch(parms).then(function(data) {
                        that.getBills(that.Head.BillSN).then(function() {
                            that.$message({
                                message: '领用成功',
                                type: 'success'
                            });
                        })
                    })

                },
                del: function(v, index) {
                    this.BillData.splice(index, 1)
                },
                back: function() {
                    window.history.back()
                },
                popup: function() {
                    var that = this
                        //parent.$('#goodsSelectWrap').show()
                    parent.$('#goodsSelectWrap').load(getRootPath() + 'new/view/GoodsQuery.html')
                },
                getInRoom: function() {
                    var that = this
                        //var DeptAccountID = this.prams.InDeptAccount.DeptAccountID
                    var DeptAccountID = JSON.parse(localStorage.getItem("deptInfo")).DeptAccountID
                    var Dep = this.conditionModel("a.DeptAccountID", null, "Equal", DeptAccountID, "String")
                    var Status = this.conditionModel("a.Status", null, "Equal", 1, "Int32")
                    var yxbz = this.conditionModel("a.yxbz ", null, "Equal", 1, "Int32")
                    var arr = [Dep, Status, yxbz]
                    var condition = this.conditionsModel(arr, "AND")
                    var parms = {
                        className: 'TwoLevelStockManager',
                        method: 'GetRoomsToDepts',
                        condition: JSON.stringify(condition),
                        userID: this.userID
                    }
                    return this._fetch(parms).then(function(data) {
                        if (data.length == 0) {
                            that.$message.error('暂无房间可选！');
                            return false
                        }
                        that.inRooms = data
                            //that.selectedRoom = data[0]
                        that.$set(that.Head, "RoomInfo", that.selectedRoom)
                    })

                },
                conditionModel: function(ColumnName, FullString, Oper, Value, Type) {

                    var obj = {
                        "ColumnName": ColumnName,
                        "FullString": FullString,
                        "Oper": Oper,
                        "Value": Value,
                        "Type": Type
                    }
                    return obj;
                },
                conditionsModel: function(Conditions, Type) {
                    var obj = {
                        "Conditions": Conditions,
                        "Type": Type
                    }
                    return obj
                },
                _fetch: function(parms) {
                    var that = this
                    return new Promise(function(resolve, reject) {
                        $.ajax({
                            type: 'POST',
                            url: getRootPath() + '/api/sendPostRequest',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json'
                            },
                            data: JSON.stringify(parms),
                            success: function(res) {

                                if (res.isSessionInvalidated) {
                                    parent.window.location.href = getRootPath() + 'login.html'
                                }
                                if (res.issuccess == 0) {
                                    var result = res.result.match(/^[ ]*$/) ? res.result : JSON.parse(res.result);
                                    resolve(result)
                                } else {
                                    that.$message.error(res.message)
                                    reject(res.message);
                                }
                            },
                            error: function(err) {
                                new Error(err)
                            }
                        });
                    });
                }

            }
        })
        window.addEventListener('message', function(e) {
            if (e.source != window.parent) return;
            var newBillData = e.data
            if (app.BillData.length > 0) {
                for (var i = 0, len = app.BillData.length; i < len; i++) {
                    if (app.BillData[i].GoodsID == newBillData.GoodsID) {
                        app.$message.error('新建物品不可重复！');
                        return false
                    }
                }
            }
            newBillData.ApplyNum = newBillData.ApplyNum || 0
            newBillData.RefPrice = newBillData.LatestPrice
            newBillData.consultMoney = newBillData.ApplyNum * newBillData.RefPrice
            app.$set(app.Head, "GoodsBookID", newBillData.GoodsBookID)
            app.$set(app.BillData, app.BillData.length, newBillData)
        })
    </script>
</body>

</html>